package service.Impl;

import DAO.*;
import DAO.impl.*;
import bean.*;
import service.UserService;
import utils.BianHaoUtils;
import utils.JdbcUtils;

import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;
import java.sql.Time;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;

/**
 * @author 栋
 * @date 2022/11/14
 * @description
 */
public class UserServiceImpl implements UserService {
    UserDAO userDAO=new UserDAOImpl();
    ItemsDAO itemsDAO=new ItemsDAOImpl();
    SchoolDAO schoolDAO=new SchoolDAOImpl();
    BankDAO bankDAO=new BankDAOImpl();
    OrdersDAO ordersDAO=new OrderDAOImpl();
    BlackListDAO blackListDAO=new BlackListDAOImpl();
    @Override
    public Users login(String phoneNumber, String pwd){
        Connection conn = null;
        Users user=null;
        try {
            conn = JdbcUtils.getConnection();
            user = userDAO.getUserByPhone(conn, phoneNumber);
            if(user!=null){
                if(!user.getUser_pwd().equals(pwd)){
                    user=null;
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.closeResoure(conn);
        }
        return user;
    }

    @Override
    public boolean register(Users u) {
        Connection conn = null;
        Users user=null;
        try {
            conn = JdbcUtils.getConnection();
            Users userByPhone = userDAO.getUserByPhone(conn, u.getPhone_number());
            if(userByPhone!=null){
                return false;
            }else{
                String userId = BianHaoUtils.getUserId();
                u.setUser_id(userId);
                userDAO.add_user(conn,u);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.closeResoure(conn);
        }
        return true;
    }

    @Override
    public List<Items> showItems(){
        Connection conn = null;
        List<Items> all_items=null;
        try {
            conn = JdbcUtils.getConnection();
            all_items = itemsDAO.getQualifiedItems(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.closeResoure(conn);
        }
        return all_items;
    }

    @Override
    public void applicationItems(Items item) {
        Connection conn = null;
        try {
            conn = JdbcUtils.getConnection();
            itemsDAO.add_item(conn,item);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.closeResoure(conn);
        }

    }

    @Override
    public boolean realName(Users user,String name, String number, String pwd, String credit_number, String cre_pwd) {
        Connection conn = null;
        try {
            conn = JdbcUtils.getConnection();
            Users userByNumber = userDAO.getUserByNumber(conn, number);
            if(userByNumber!=null){
                //该学号已经注册过了
                return false;
            }
            School stuInfByNumber = schoolDAO.getStuInfByNumber(conn, number);
            if(stuInfByNumber==null){
                //学号不存在
                return false;
            }
            if(!(stuInfByNumber.getStu_pwd().equals(pwd)&&stuInfByNumber.getStu_name().equals(name))){
                //信息不符合
                return false;
            }
            Bank creditByNumber = bankDAO.getCreditByNumber(conn, credit_number);
            if(creditByNumber==null){
                //银行卡号不存在
                return false;
            }
            if(!creditByNumber.getPwd().equals(cre_pwd)){
                //信息不符合
                return false;
            }
            user.setStu_number(number);
            user.setCredit_number(credit_number);
            userDAO.update_user(conn,user);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.closeResoure(conn);
        }

        return true;
    }

    @Override
    public Items showItemInfor(String item_id) {
        Connection conn = null;
        Items item = null;
        try {
            conn = JdbcUtils.getConnection();
            item = itemsDAO.getItemById(conn, item_id);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.closeResoure(conn);
        }
        return item;
    }

    @Override
    public List<Items> showPersonalItems(String user_id) {
        Connection conn = null;
        List<Items> itemsByOwer = null;
        try {
            conn = JdbcUtils.getConnection();
            itemsByOwer = itemsDAO.getItemsByOwer(conn, user_id);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.closeResoure(conn);
        }
        return itemsByOwer;

    }

    @Override
    public boolean updateInfor(Users user) {
        Connection conn = null;
        try {
            conn = JdbcUtils.getConnection();
            userDAO.update_user(conn,user);
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.closeResoure(conn);
        }
        return false;
    }

    @Override
    public int deleteItem(String item_id) {
        Connection conn = null;
        int ret=0;
        try {
            conn = JdbcUtils.getConnection();
            ret = itemsDAO.delet_item(conn, item_id);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.closeResoure(conn);
        }
       return ret;
    }

    @Override
    public List<Items> showItemsByType(int type) {
        List<Items> itemsByType = null;
        Connection conn=null;
        try {
           conn = JdbcUtils.getConnection();
            itemsByType = itemsDAO.getItemsByType(conn, type);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.closeResoure(conn);
        }
        return itemsByType;
    }

    @Override
    public List<Items> showItemsSearch(String name) {
        Connection conn = null;
        List<Items> itemsBySearch = null;
        try {
            conn = JdbcUtils.getConnection();
            itemsBySearch = itemsDAO.getItemsBySearch(conn, name);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.closeResoure(conn);
        }

        return itemsBySearch;
    }

    @Override
    public String buyItems(Orders orders,String credit_number, String pwd) {
        Connection conn = null;
        try {
            conn = JdbcUtils.getConnection();
            Bank creditCar = bankDAO.getCreditByNumber(conn, credit_number);
            if(!creditCar.getPwd().equals(pwd)){
                //银行卡密码错误
                return "银行卡密码错误";
            }else if(creditCar.getMoney().compareTo(orders.getTotal_price())==-1){
                //余额不足
                return "余额不足";
            }
            //减去商品数量
            Items item = itemsDAO.getItemById(conn, orders.getItem_id());
            if(item.getItem_count()<orders.getBuy_count()) {
                return "商品余额不足";

            }
            item.setItem_count(item.getItem_count()-orders.getBuy_count());
            itemsDAO.update_item(conn,item);
            //保存订单
            String orderId = BianHaoUtils.getOrderId();
            orders.setOrder_id(orderId);
            ordersDAO.add_order(conn,orders);

            //扣钱
            creditCar.setMoney(creditCar.getMoney().subtract(orders.getTotal_price()));
            Bank mainCard = bankDAO.getCreditByNumber(conn, "0000001");
            mainCard.setMoney(mainCard.getMoney().add(orders.getTotal_price()));
            bankDAO.updateCard(conn,creditCar);
            bankDAO.updateCard(conn,mainCard);


        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.closeResoure(conn);
        }
        return "购买成功";
    }

    @Override
    public String payAll(Users user, Car car, String credit_pwd,Date date,Time time) {
        Connection conn = null;
        try {
            conn = JdbcUtils.getConnection();
            Bank card = bankDAO.getCreditByNumber(conn, user.getCredit_number());

            if(!card.getPwd().equals(credit_pwd)){
                //检测银行卡密码是否正确
                return "银行卡密码错误";
            }else if(card.getMoney().compareTo(car.getTotalPrice())==-1){
                //检测银行卡余额是否足够
                return "银行卡余额不足";
            }
            //生成订单
            List<Orders> orders=car.getLst();
            for (Orders order : orders) {
                order.setOrder_id(BianHaoUtils.getOrderId());
                Items item = itemsDAO.getItemById(conn, order.getItem_id());
                if(item.getItem_count()<order.getBuy_count())
                {
                    return "商品"+item.getItem_id()+"数量不足";
                }
                item.setItem_count(item.getItem_count()-order.getBuy_count());
                itemsDAO.update_item(conn,item);
                order.setBuy_date(date);
                order.setBuy_time(time);
                ordersDAO.add_order(conn,order);
                car.del(order);
            }
            //扣除银行卡里的钱
            card.setMoney(card.getMoney().subtract(car.getTotalPrice()));
            Bank mainCard=bankDAO.getCreditByNumber(conn,"0000001");
            mainCard.setMoney(mainCard.getMoney().add(car.getTotalPrice()));
            bankDAO.updateCard(conn,card);
            bankDAO.updateCard(conn,mainCard);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.closeResoure(conn);
        }

        return "购买成功";
    }

    @Override
    public List<Orders> showOrders(String user_id ,String option) {
        Connection conn = null;
        List<Orders> orders = null;
        try {
            conn = JdbcUtils.getConnection();
            if(option.equals("0")){
                orders = ordersDAO.getOrdersByUser_id(conn, user_id);
            }else if(option.equals("-1")){
                orders=ordersDAO.getOrderByOwer_id(conn,user_id);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.closeResoure(conn);
        }
        return orders;
    }

    @Override
    public void confirmOrder(String order_id) {
        Connection conn = null;
        try {
            conn = JdbcUtils.getConnection();
            Orders orderById = ordersDAO.getOrderById(conn, order_id);
            orderById.setArrival("是");
            ordersDAO.updateOrder(conn,orderById);
            //将钱转到卖家账户
            Items item = itemsDAO.getItemById(conn, orderById.getItem_id());
            Users userById = userDAO.getUserById(conn, item.getOwer_id());
            Bank card = bankDAO.getCreditByNumber(conn, userById.getCredit_number());
            Bank mainCard = bankDAO.getCreditByNumber(conn, "0000001");
            card.setMoney(card.getMoney().add(orderById.getTotal_price()));
            mainCard.setMoney(mainCard.getMoney().subtract(orderById.getTotal_price()));
            bankDAO.updateCard(conn,card);
            bankDAO.updateCard(conn,mainCard);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.closeResoure(conn);
        }

    }

    @Override
    public boolean isInBlacklist(String user_id) {
        Connection conn = null;
        try {
            conn = JdbcUtils.getConnection();
            BlackList blackById = blackListDAO.getBlackById(conn, user_id);
            if(blackById==null){
                return false;
            }else{
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.closeResoure(conn);
        }
        return false;
    }


}
